#include <iostream>
#include "vector"
#include "algorithm"

using namespace std;

/*
 * 常用的集合算法  注  集合必须有序
 *      set_intersection(iterator begin1, iterator end1, iterator begin2, iterator end2, iterator dest)
 *              求两个容器的交集    返回值为交集中最后一个元素的下一个位置的迭代器
 *      set_union(iterator begin1, iterator end1, iterator begin2, iterator end2, iterator dest)
 *              求两个容器的并集    返回值为并集中最后一个元素的下一个位置的迭代器
 *      set_difference(iterator begin1, iterator end1, iterator begin2, iterator end2, iterator dest)
 *              求两个容器的差集    返回值为差集中最后一个元素的下一个位置的迭代器
 */

class MyPrint{
public:
    void operator()(int value){
        cout << value << " ";
    }
};

void test01(){
    vector<int> v1;
    vector<int> v2;

    for (int i = 0; i < 10; ++i) {
        v1.push_back(i);
        v2.push_back(i+5);
    }
    cout << "v1中数" << endl;
    for_each(v1.begin(), v1.end(), MyPrint());
    cout << endl;
    cout << "v2中数" << endl;
    for_each(v2.begin(), v2.end(), MyPrint());

    vector<int> v3;
    v3.resize(min(v1.size(), v2.size()));   // v3最坏情况是v1和v2中最少元素的全部元素
    vector<int>::iterator it = set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
    cout << endl;
    cout << "v3中数" << endl;
    for_each(v3.begin(), it, MyPrint());
    cout << endl;
}

void test02(){
    vector<int> v1;
    vector<int> v2;

    for (int i = 0; i < 10; ++i) {
        v1.push_back(i);
        v2.push_back(i+5);
    }
    cout << "v1中数" << endl;
    for_each(v1.begin(), v1.end(), MyPrint());
    cout << endl;
    cout << "v2中数" << endl;
    for_each(v2.begin(), v2.end(), MyPrint());

    vector<int> v3;
    v3.resize(max(v1.size(), v2.size()));
    vector<int>::iterator it = set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
    cout << endl;
    cout << "v1和v2的差集" << endl;
    for_each(v3.begin(), it, MyPrint());
    cout << endl;

    vector<int> v4;
    v4.resize(max(v1.size(), v2.size()));
    vector<int>::iterator it2 = set_difference(v2.begin(), v2.end(), v1.begin(), v1.end(), v4.begin());
    cout << endl;
    cout << "v2和v1的差集" << endl;
    for_each(v4.begin(), it2, MyPrint());
    cout << endl;
}

int main() {

    test01();
    test02();

    return 0;
}
